/**
 * 
 */
package marpg.protocol;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * @author Steven
 * 
 */
public class MessageHandler {
	private static JAXBContext jaxbContext;
	private static Marshaller marshaller;
	private static Unmarshaller unmarshaller;

	public MessageHandler() {
		try {
			jaxbContext = JAXBContext.newInstance("marpg.protocol");
			marshaller = jaxbContext.createMarshaller();
			unmarshaller = jaxbContext.createUnmarshaller();
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}

	public String composeMessage(MARPG message) {
		StringWriter writer = new StringWriter();

		try {
			marshaller.marshal(message, writer);
			writer.flush();
		} catch (JAXBException e) {
			e.printStackTrace();
		}

		return writer.toString();
	}

	public MARPG decomposeMessage(String message) {
		MARPG marpgObj = null;

		try {
			StringReader reader = new StringReader(message);
			marpgObj = (MARPG) unmarshaller.unmarshal(reader);
			reader.close();
		} catch (JAXBException e) {
			//e.printStackTrace();
			System.err.println("Invalid XML.");
		}

		return marpgObj;
	}
}
